# etbox_client.py - 客户端上传处理器
# coder DarionDong 
import os
import sys
import json
import threading
import time
import tkinter as tk
from tkinter import ttk, messagebox
import win32pipe
import win32file
import pywintypes

class UploadProgressWindow:
    """上传进度窗口"""
    def __init__(self, filename):
        self.root = tk.Tk()
        self.root.title("上传到ETBOX")
        self.root.geometry("450x220")
        self.root.resizable(False, False)
        
        # 设置窗口图标
        try:
            self.root.iconbitmap(default="etbox.ico")
        except:
            pass
        
        # 屏幕居中
        self.root.update_idletasks()
        x = (self.root.winfo_screenwidth() - self.root.winfo_width()) // 2
        y = (self.root.winfo_screenheight() - self.root.winfo_height()) // 2
        self.root.geometry(f"+{x}+{y}")
        
        # 图标和标题
        header_frame = tk.Frame(self.root)
        header_frame.pack(fill="x", padx=20, pady=15)
        
        tk.Label(header_frame, text="📤", font=("Arial", 24)).pack(side="left")
        title_frame = tk.Frame(header_frame)
        title_frame.pack(side="left", padx=10)
        tk.Label(title_frame, text="上传到ETBOX", font=("Arial", 12, "bold")).pack(anchor="w")
        tk.Label(title_frame, text=filename, font=("Arial", 10), fg="gray").pack(anchor="w")
        
        # 进度条
        progress_frame = tk.Frame(self.root)
        progress_frame.pack(fill="x", padx=20, pady=10)
        
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(
            progress_frame, 
            variable=self.progress_var, 
            maximum=100,
            length=400,
            mode='determinate'
        )
        self.progress_bar.pack()
        
        # 进度信息
        info_frame = tk.Frame(self.root)
        info_frame.pack(fill="x", padx=20, pady=5)
        
        self.percentage_label = tk.Label(info_frame, text="0%", font=("Arial", 14, "bold"))
        self.percentage_label.pack()
        
        self.detail_label = tk.Label(info_frame, text="准备上传...", font=("Arial", 9), fg="gray")
        self.detail_label.pack()
        
        # 状态信息
        self.status_label = tk.Label(self.root, text="正在连接上传服务...", font=("Arial", 9))
        self.status_label.pack(pady=10)
        
        self.start_time = time.time()
        self.last_update_time = time.time()
        self.last_progress = 0
    
    def update_progress(self, progress, status=""):
        """更新进度显示"""
        self.progress_var.set(progress)
        self.percentage_label.config(text=f"{progress:.1f}%")
        
        current_time = time.time()
        if current_time - self.last_update_time >= 1.0 and progress > self.last_progress:
            # 计算速度
            progress_diff = progress - self.last_progress
            time_diff = current_time - self.last_update_time
            
            if progress_diff > 0:
                speed = progress_diff / time_diff
                if speed > 0:
                    remaining = (100 - progress) / speed
                    if remaining < 60:
                        time_text = f"剩余时间: {remaining:.0f}秒"
                    else:
                        time_text = f"剩余时间: {remaining/60:.1f}分钟"
                    
                    self.status_label.config(text=f"速度: {speed:.1f}%/秒 | {time_text}")
            
            self.last_progress = progress
            self.last_update_time = current_time
        
        if status:
            self.status_label.config(text=status)
        
        self.root.update_idletasks()
    
    def complete(self, success, message):
        """上传完成"""
        if success:
            self.status_label.config(text="上传完成！", fg="green")
            self.progress_var.set(100)
            self.percentage_label.config(text="100%", fg="green")
            
            # 3秒后自动关闭
            self.root.after(3000, self.root.destroy)
        else:
            self.status_label.config(text=f"上传失败: {message}", fg="red")
            # 失败时显示关闭按钮
            close_button = tk.Button(self.root, text="关闭", command=self.root.destroy, width=15)
            close_button.pack(pady=10)
    
    def run(self):
        """运行窗口"""
        self.root.mainloop()

def simulate_progress(progress_window):
    """模拟进度更新"""
    for i in range(0, 101, 2):
        progress_window.update_progress(i, f"上传中... {i}%")
        time.sleep(0.1)
    
    # 等待实际结果
    time.sleep(1)

def send_upload_request(file_path):
    """发送上传请求到服务"""
    try:
        # 连接到命名管道
        handle = win32file.CreateFile(
            r"\\.\pipe\etbox_upload_pipe",
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0,
            None,
            win32file.OPEN_EXISTING,
            0,
            None
        )
        
        # 发送文件路径
        win32file.WriteFile(handle, file_path.encode('utf-8'))
        
        # 读取结果
        result = win32file.ReadFile(handle, 65536)
        result_data = json.loads(result[1].decode('utf-8'))
        
        win32file.CloseHandle(handle)
        return result_data
        
    except pywintypes.error as e:
        return {"success": False, "message": f"无法连接到上传服务: {e}"}

def handle_upload_request(file_path):
    """处理上传请求"""
    if not os.path.exists(file_path):
        messagebox.showerror("错误", f"文件不存在: {file_path}")
        return
    
    # 创建进度窗口
    progress_window = UploadProgressWindow(os.path.basename(file_path))
    
    def do_upload():
        # 先模拟进度
        simulate_progress(progress_window)
        
        # 然后发送实际请求
        result = send_upload_request(file_path)
        
        # 显示结果
        progress_window.complete(result["success"], result["message"])
    
    # 在新线程中执行上传
    upload_thread = threading.Thread(target=do_upload, daemon=True)
    upload_thread.start()
    
    # 运行窗口
    progress_window.run()